<?php

class Model_Person extends Model_Base
{

    /**
     * Database table name
     *
     * @var string
     */
    protected $name = "person";

    /**
     * Lists all persons, ordered alphabetically by last name.
     * @param String $where optional where clause
     * @return type array an array of (associative) arrays
     */
    public function listAll($where = NULL)
    {
	$select = $this->db->select()
		->from($this->name)
		->order('surname ASC');

	if ($where != NULL)
	{
	    $select->where($where);
	}

	return $this->db->fetchAll($select);
    }

    public function listByPersonTypes($personTypes)
    {
	$select = $this->db->select()
		->from($this->name)
		->order('surname ASC');
	foreach ($personTypes as $personType)
	{
	    $select->orWhere('person_type = ?', $personType);
	}
	return $this->db->fetchAll($select);
    }

    /**
     * Creates a person
     * @param array $person
     */
    public function create($person)
    {
	if (!is_array($person))
	{
	    throw new InvalidArgumentException("Argument is " . gettype($person));
	}

	try
	{
	    $this->db->insert($this->name, $person);
	} catch (Zend_Db_Statement_Exception $e)
	{
	    throw new InvalidArgumentException("Argument is " . gettype($person) . ". Nested message is: " . $e->getMessage());
	}
    }

    /**
     * Updates a person's data.
     * 
     * @param array $person the person's data
     */
    public function update(array $person)
    {
	$where = $this->db->quoteInto('id = ?', $person['id']);
	$this->db->update($this->name, $person, $where);
    }

    /**
     * Get a person's data. The person is identified by its id.
     * 
     * @param type $id the person's id
     * @return array the person's data, or FALSE if not found
     */
    public function find($id)
    {
	$select = $this->db->select()
		->from($this->name)
		->where('id = ?', $id);
	return $this->db->fetchRow($select);
    }

    /**
     * Removes a person from the database identified by its id.
     * 
     * @param type $id the person's id
     */
    public function delete($id)
    {
	$where = $this->db->quoteInto('id = ?', $id);
	$this->db->delete($this->name, $where);
    }

    /**
     * Removes all persons from the database
     * 
     * @param type $id the person's id
     */
    public function deleteAll()
    {
	$this->db->delete($this->name);
    }

    /**
     * Returns the last person that was created in the table
     * @return type array the person's data, or FALSE if not found
     */
    public function lastCreated()
    {
	$lastInsertedId = $this->db->lastInsertId($this->name);
	$lastInsertedPerson = $this->find($lastInsertedId);
	return $lastInsertedPerson;
    }

}

